<?php

namespace app\api\controller;
use think\Db;
class Login extends Base {
    /**
     * 账号密码登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0参数错误，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功
     */
    public  function userLogin(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['pass'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $pass = $_POST['pass'];
        if(preg_match("/^1[3456789]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json_encode(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                if(empty($username)){
                    return json_encode(['status'=>3,'msg'=>'该手机号未注册，无法登陆']);
                }else{
                    if($username['user_password'] != md5($pass)){
                        return json_encode(['status'=>4,'msg'=>'密码错误']);
                    }else{
                        if($username['user_status'] == 2){
                            return json_encode(['status'=>100,'msg'=>'账号冻结']);
                        }else{
                            //更新token
                            $token = md5(date('YmdHis') . rand(100000,999999));
                            Db::table('up_u_user')->where('user_phone',$phone)
                                ->update(['user_token'=>$token,'user_login_status'=>1]);
                            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                            return json_encode(['status'=>200,'msg'=>$username]);
                        }
                    }
                }
            }
        }else{
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
    }

    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是登录 2是注册 3是忘记密码，第三方登录和快捷登录传4)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
    public  function getPhoneCode(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['type'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $num = rand(100000,999999);
        $phone = $_POST['phone'];
        $type = $_POST['type'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if($type != 4){
            if(empty($username) && $type==1){
                return json_encode(['status'=>21,'msg'=>'没有此手机号码用户']);
            }
            if(empty($username) && $type==3){
                return json_encode(['status'=>21,'msg'=>'没有此手机号码用户']);
            }
            if(!empty($username) && $type==2){
                return json_encode(['status'=>22,'msg'=>'已经有此手机号码用户']);
            }
        }else{
            if($username['user_wx_token']){
                return json_encode(['status'=>22,'msg'=>'此手机号已经绑定了']);
            }
        }
        $sendres = $this->duaxin($phone,$num);
        if($sendres['code'] != '00000'){
            return json_encode(['status'=>3,'msg'=>'短信平台错误：'.$sendres['msg']]);
        }else {
            //=============================
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'status' => 0]);
            } else {
                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
            }
            if (!$res) {
                return json_encode(['status' => 31, 'msg' => '数据库操作失败']);
            }
            //===============================================
            return json_encode(['status' => 200, 'msg' => md5($num)]);
        }
    }

    /**
     * 忘记密码第一步
     * @return bool
     * 参数：phone,code，newpass
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function forgetPassOne(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 3601){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        return json_encode(['status'=>200,'msg'=>'ok']);
    }

    /**
     * 忘记密码第二步
     * @return bool
     * 参数：phone,code，newpass
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function forgetPassTwo(){
        $phone = $_POST['phone'];
        $new = $_POST['newpass'];
        $token = md5(date('YmdHis').rand(100000,999999));
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_password'=>md5($new),'user_token'=>$token]);
        Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
        if($res){
            $token = md5(date('YmdHis') . rand(100000,999999));
            Db::table('up_u_user')->where('user_phone',$phone)
                ->update(['user_token'=>$token,'user_login_status'=>1]);
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>3,'msg'=>'密码重置失败']);
        }
    }


    //================第三方登录====================

    /**
     * 微信或者qq登录
     * wqtoken,type(1是微信，2是qq)
     * @return string
     */
    public  function wqLogin()
    {
        header("Access-Control-Allow-Origin:*");
        $wxtoken = $_POST['wqtoken'];
        $field = 'user_wx_token';
        $username = Db::table('up_u_user')->where($field, $wxtoken)->find();
        if (!empty($username)) {
            $token = md5(date('YmdHis') . rand(100000, 999999));
            $res = Db::table('up_u_user')->where($field, $wxtoken)->update(['user_token' => $token,'user_login_status'=>2]);
            if ($res) {
                //===禁用和启用====
                if($username['user_status'] != 1){
                    return json_encode(['status' => 0, 'msg' => '对不起，您无权登录，请联系客服']);
                }
                //======end======
                $user = Db::table('up_u_user')->where($field, $wxtoken)->find();
                return json_encode(['status' => 200, 'msg' => $user]);
            } else {
                return json_encode(['status' => 3, 'msg' => '数据库出错']);
            }
        }else{
            return json_encode(['status' => 404, 'msg' => '查无此人']);
        }

    }
    /**
     * 微信或者qq第一次登录
     * wqtoken，phone，code，name，image，type
     * @return string
     */
    public  function wqFirstLogin()
    {
//        header("Access-Control-Allow-Origin:*");
        $wqtoken = $_POST['wqtoken'];
        $field = '_wx_';
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $name = $_POST['name'];
        $image = $_POST['image'];
//        $pass = $_POST['pass'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if($code==''){
            return json_encode(['status'=>4,'msg'=>'有未填项，请检查']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 3601){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        //=============================================
        if(!empty($username)){
            //===禁用和启用====
            if($username['user_status'] != 1){
                return json_encode(['status' => 0, 'msg' => '对不起，您无权登录，请联系客服']);
            }
            //======end======
            if($username['user'.$field.'token']){
                return json_encode(['status'=>3,'msg'=>'已经有此手机号码用户绑定了']);
            }else{
                $token = md5(date('YmdHis').rand(100000,999999));
                $data = array();
                $data['user_token'] = $token;
                $data['user'.$field.'token'] = $wqtoken;
                $data['user'.$field.'nickname'] = $name;
                $data['user'.$field.'image'] = $image;
                $data['user_login_status'] = 2;
                if(!$username['user_username']){
                    $data['user_username'] = $name;
                }
                if(!$username['user_image']){
                    $data['user_image'] = $image;
                }
                $res = Db::table('up_u_user')->where('user_phone',$phone)->update($data);
                if($res){
                    $user = Db::table('up_u_user')
                        ->where('user_phone',$phone)
                        ->find();
                    Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
                    return json_encode(['status'=>200,'msg'=>$user]);
                }else{
                    return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
                }
            }
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user'.$field.'token'] = $wqtoken;
        $data['user'.$field.'nickname'] = $name;
        $data['user'.$field.'image'] = $image;
        $data['user_image'] = $image;//用户名字和头像同步一下
        $data['user_username'] = $name;//
        $data['user_where'] = 1;//
        $data['user_login_status'] = 2;
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')
                ->where('user_id',$id)
                ->find();
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
        }

    }

    //***********************个人资料及修改************************
    /**
     * uploadLocality图片上传至本地&压缩
     */
    public function uploadImage(){
        $tmp = $_FILES['image']['tmp_name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json_encode(['status'=>0,'msg'=>"图片不得超过5M！"]);
        }
        $today = date('Ymd');
        $dir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/images/' . $today;
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
//        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $newName = $rand . '.png';
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/{$newName}")){
                $imgUrl = "/uploads/images/$today/$newName";
                if($size > 1024*1024*2){
                    $this->image_png_size_add("{$dir}/{$newName}","{$dir}/{$newName}");
                }
                return json_encode(['status'=>200,'msg'=>$imgUrl]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>"上传一张图！"]);
        }
    }
    /**
     * 个人资料
     *
     */
    public function myInfo()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            return json_encode(['status'=>301,'msg'=>"Token失效！请重新登录！"]);
        }
        $user = Db::table('up_u_user')->alias('u')
            ->join('up_department d','u.user_depart_id=d.department_id','LEFT')
            ->where('user_id',$user_id)
            ->find();
        return json_encode(['status'=>200,'msg'=>$user]);
    }
    /**
     * 获取部门列表
     */
    public function getDepart()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            return json_encode(['status'=>301,'msg'=>"Token失效！请重新登录！"]);
        }
        $data = Db::table('up_department')->select();
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 修改头像或者昵称等
     *
     */
    public function updateInfo(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //1、我是不是可以修改：只有是第三方的才可以，后台指定的都不能改
        $can = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_role,user_where')
            ->find();
//        if($can['user_role'] == 2 || $can['user_where'] == 2){
//            return json_encode(['status'=>0,'msg'=>'您无权修改']);
//        }
        //2、有什么改什么
        $update = array();
        if(isset($name)){
            $update['user_username'] = $name;
        }
        if(isset($thumb)){
            $update['user_image'] = $thumb;
        }
        if(isset($sex)){
            $update['user_gender'] = $sex;
        }
        if(isset($birthday)){
            $update['user_birthday'] = $birthday;
        }
        //职位三联
        if(isset($depart_id)){
            $update['user_depart_id'] = $depart_id;
        }
        if(isset($zhiwei)){
            $update['user_zhiwei'] = $zhiwei;
        }
        if(isset($zhize)){
            $update['user_zhize'] = $zhize;
        }
        Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->update($update);
        return json_encode(['status'=>200,'msg'=>'ok']);
    }
    /**
     * 获取首页的帮助信息
     */
    public function getHelpInfo(){
        extract(input());
        $data = Db::table('up_about')
            ->where('a_id',2)
            ->find();
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 获取注册协议
     */
    public function getZhuceInfo(){
        extract(input());
        $data = Db::table('up_about')
            ->where('a_id',1)
            ->find();
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    public function test(){
        $a = date('Y-m-d H:i:s');
        $b = '2018-12-14';
        if($b < $a){
            echo 1;
        }else{
            echo 2;
        }
    }
}